package com.ruoyi.app.common

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.RandomUtil
import cn.hutool.json.JSONUtil
import com.aliyun.mts20210728.Client
import com.aliyun.mts20210728.models.QueryCopyrightExtractRequest
import com.aliyun.mts20210728.models.QueryCopyrightRequest
import com.aliyun.mts20210728.models.SubmitCopyrightExtractRequest
import com.aliyun.mts20210728.models.SubmitCopyrightJobRequest
import com.aliyun.tea.*
import com.aliyun.teaopenapi.models.Config
import com.ruoyi.exception.FlyException


/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
@Throws(Exception::class)
fun createVideoClient(): Client {
    val config = Config() // 必填，您的 AccessKey ID
        .setAccessKeyId(ACCESS_KEY) // 必填，您的 AccessKey Secret
        .setAccessKeySecret(ACCESS_SECRET)
    // Endpoint 请参考 https://api.aliyun.com/product/Mts
    config.endpoint = "mts.cn-shanghai.aliyuncs.com"
    return Client(config)
}

fun String.selectCyJob(): String =
    createVideoClient().let { client ->

        var message: String = ""
        client.submitCopyrightExtract(SubmitCopyrightExtractRequest().apply {
            input = """
                {"Bucket":"yanlv-video","Location":"oss-cn-shanghai","Object":"${fileName()}"}
            """.trimIndent()
            url = this@selectCyJob
        }).let { submitCopyrightJobResponse ->
            if (submitCopyrightJobResponse.body.statusCode != 200L) throw FlyException(submitCopyrightJobResponse.body.message)
            else {
                val jobId = submitCopyrightJobResponse.body.data.jobId
                while (true) {
                    val queryCopyrightResponse = client.queryCopyrightExtract(QueryCopyrightExtractRequest().apply {
                        this.jobId = jobId
                    })
                    if (queryCopyrightResponse.body.message == "job is processing, please try again later") {
                        continue
                    } else {
                        message = queryCopyrightResponse.body.data.message
                        break
                    }
                }
                message
            }

        }
    }

fun String.createCyJob(id: Long, userId: Long): String =
    createVideoClient().let { client ->
        var resultUrl: String
        client.submitCopyrightJob(SubmitCopyrightJobRequest().apply {
            input = """
                {"Bucket":"yanlv-video","Location":"oss-cn-shanghai","Object":"${fileName()}"}
            """.trimIndent()
            level = 2
            message = aigc(id, userId)
            startTime = 0
            totalTime = 360
            url = this@createCyJob
//            visibleMessage = "userId24"
            output = """
                {"Bucket":"yanlv-video","Location":"oss-cn-shanghai","Object":"${RandomUtil.randomNumbers(6)}.mp4"}
            """.trimIndent()
        }).let { submitCopyrightJobResponse ->
            if (submitCopyrightJobResponse.body.statusCode != 200L) throw FlyException(submitCopyrightJobResponse.body.message)
            else {
                val jobId = submitCopyrightJobResponse.body.data.jobId
                println("当前处理得jobId为: $jobId, 请求id是: ${submitCopyrightJobResponse.body.requestID}")
                while (true) {
                    val queryCopyrightResponse = client.queryCopyright(QueryCopyrightRequest().apply {
                        this.jobId = jobId
                    })
                    val queryCopyrightResponseBodyData = queryCopyrightResponse.body.data[0]
                    if (queryCopyrightResponseBodyData.status != "success" && queryCopyrightResponseBodyData.status != "failed") {
                        continue
                    } else {
                        val resultOjb = JSONUtil.parseObj(queryCopyrightResponseBodyData.result)
                        if (resultOjb.getStr("Code") != "success")
                            throw FlyException(resultOjb.getStr("Message"))
                        else {
                            JSONUtil.parseObj(queryCopyrightResponseBodyData.output).let { outPut ->
                                resultUrl =
                                    "https://yanlv-video.oss-cn-shanghai.aliyuncs.com//${outPut.getStr("Object")}"
                            }
                            break
                        }
                    }
                }
            }
        }
        resultUrl
    }


fun String.fileName(): String = FileUtil.getName(this)


fun main() {
    println(
        "https://yanlv-video.oss-cn-shanghai.aliyuncs.com/face_program/1711702855570_%E8%A7%86%E9%A2%91%E6%8F%90%E5%8F%96.mp4".createCyJob(
            20,
            154721
        ).also { println("当前溯源得原始地址是: $it") }
            .let {
                println("视频溯源水印 解码成功, 当前解码得结果是: ${it.selectCyJob()}")
            }
    )
    //println("视频溯源水印 解码成功, 当前解码得结果是: ${"https://yanlv-video.oss-cn-shanghai.aliyuncs.com//480994.mp4".selectCyJob()}")

}